package com.example.aiquestions.service.impl;

import com.example.aiquestions.entity.*;
import com.example.aiquestions.mapper.QuestionMapper;
import com.example.aiquestions.model.dto.QuestionDetail;
import com.example.aiquestions.model.dto.QuestionResponse.QuestionData;
import com.example.aiquestions.service.QuestionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    @Transactional
    public List<Long> saveQuestions(List<QuestionData> questionsData) {
        List<Long> questionIds = new ArrayList<>();
        
        for (QuestionData questionData : questionsData) {
            // 保存基本题目信息
            Question question = new Question();
            question.setQuestionType(questionData.getQuestionType());
            question.setStem(questionData.getStem());
            question.setAnalysis(questionData.getAnalysis());
            question.setDifficulty(questionData.getDifficulty());
            question.setTotalScore(questionData.getTotalScore());

            // 根据题目类型设置答案和其他特定字段
            switch (questionData.getQuestionType()) {
                case "SINGLE_CHOICE":
                    question.setAnswer(questionData.getAnswer());
                    break;
                case "TRUE_FALSE":
                    question.setAnswer(questionData.getAnswer());
                    break;
                case "FILL_BLANK":
                    question.setBlanks(String.join("|", questionData.getBlanks()));
                    question.setScore(questionData.getScore());
                    break;
                case "READING":
                    question.setPassage(questionData.getPassage());
                    break;
                case "SHORT_ANSWER":
                    question.setAnswer(questionData.getAnswer());
                    break;
            }

            // 插入题目并获取ID
            questionMapper.insertQuestion(question);
            Long questionId = question.getId();
            questionIds.add(questionId);

            // 保存选项（选择题）
            if (questionData.getOptions() != null) {
                for (QuestionData.Option option : questionData.getOptions()) {
                    QuestionOption questionOption = new QuestionOption();
                    questionOption.setQuestionId(questionId);
                    questionOption.setOptionId(option.getOptionId());
                    questionOption.setContent(option.getContent());
                    questionMapper.insertOption(questionOption);
                }
            }

            // 保存多选题答案
            if ("MULTIPLE_CHOICE".equals(questionData.getQuestionType()) && questionData.getAnswers() != null) {
                for (String answer : questionData.getAnswers()) {
                    MultipleChoiceAnswer multiAnswer = new MultipleChoiceAnswer();
                    multiAnswer.setQuestionId(questionId);
                    multiAnswer.setOptionId(answer);
                    questionMapper.insertMultipleChoiceAnswer(multiAnswer);
                }
            }

            // 保存简答题答案要点
            if ("SHORT_ANSWER".equals(questionData.getQuestionType()) && questionData.getKeyPoints() != null) {
                for (QuestionData.KeyPoint keyPoint : questionData.getKeyPoints()) {
                    AnswerKeyPoint answerKeyPoint = new AnswerKeyPoint();
                    answerKeyPoint.setQuestionId(questionId);
                    answerKeyPoint.setPoint(keyPoint.getPoint());
                    answerKeyPoint.setScore(keyPoint.getScore());
                    questionMapper.insertKeyPoint(answerKeyPoint);
                }
            }

            // 保存阅读理解子题目
            if ("READING".equals(questionData.getQuestionType()) && questionData.getSubQuestions() != null) {
                for (QuestionData.SubQuestion subQuestion : questionData.getSubQuestions()) {
                    Question subQuestionEntity = new Question();
                    subQuestionEntity.setQuestionType("SUB_QUESTION");
                    subQuestionEntity.setParentId(questionId);
                    subQuestionEntity.setStem(subQuestion.getStem());
                    subQuestionEntity.setAnswer(subQuestion.getAnswer());
                    subQuestionEntity.setAnalysis(subQuestion.getAnalysis());
                    subQuestionEntity.setScore(subQuestion.getScore());
                    questionMapper.insertQuestion(subQuestionEntity);

                    // 保存子题目的选项（如果有）
                    if (subQuestion.getOptions() != null) {
                        for (QuestionData.Option option : subQuestion.getOptions()) {
                            QuestionOption questionOption = new QuestionOption();
                            questionOption.setQuestionId(subQuestionEntity.getId());
                            questionOption.setOptionId(option.getOptionId());
                            questionOption.setContent(option.getContent());
                            questionMapper.insertOption(questionOption);
                        }
                    }
                }
            }

            // 保存标签
            if (questionData.getTags() != null) {
                for (String tag : questionData.getTags()) {
                    questionMapper.insertTag(questionId, tag);
                }
            }

            // 保存知识点
            if (questionData.getKnowledgePoints() != null) {
                for (String knowledgePoint : questionData.getKnowledgePoints()) {
                    questionMapper.insertKnowledgePoint(questionId, knowledgePoint);
                }
            }
        }
        return questionIds;
    }

    @Override
    public QuestionDetail getQuestionById(Long id) {
        QuestionDetail detail = questionMapper.getQuestionWithDetailsById(id);
        return detail;
    }

    @Override
    public List<QuestionDetail>  getQuestionsByIds(List<Long> ids) {
        List<QuestionDetail> list = questionMapper.getQuestionsByIds(ids);

        return list;
    }

    /**
     *
     * @param id 题目ID
     * @return
     */
    @Override
    @Transactional
    public boolean deleteQuestionById(Long id) {
        // 检查题目是否存在
        Question question = questionMapper.getQuestionById(id);
        if (question == null) {
            throw new IllegalArgumentException("题目不存在：" + id);
        }

        // 如果是阅读理解题，先删除所有子题目
        if ("READING".equals(question.getQuestionType())) {
            List<Long> subQuestionIds = questionMapper.getSubQuestionIds(id);
            for (Long subId : subQuestionIds) {
                deleteRelatedData(subId);
                questionMapper.deleteQuestionById(subId);
            }
        }

        // 删除题目相关的所有数据
        deleteRelatedData(id);

        // 删除题目本身
        return questionMapper.deleteQuestionById(id) > 0;
    }

    /**
     * 删除题目相关的所有数据（选项、答案、标签等）
     */
    private void deleteRelatedData(Long questionId) {
        questionMapper.deleteQuestionOptions(questionId);
        questionMapper.deleteMultipleChoiceAnswers(questionId);
        questionMapper.deleteKeyPoints(questionId);
        questionMapper.deleteTags(questionId);
        questionMapper.deleteKnowledgePoints(questionId);
    }

    /**
     * 更新题目
     * @param id 题目ID
     * @param questionData 更新后的题目数据
     * @return
     */
    @Override
    @Transactional
    public QuestionDetail updateQuestion(Long id, QuestionData questionData) {
        // 检查题目是否存在
        Question question = questionMapper.getQuestionById(id);
        if (question == null) {
            throw new IllegalArgumentException("题目不存在：" + id);
        }

        // 更新基本信息
        question.setQuestionType(questionData.getQuestionType());
        question.setStem(questionData.getStem());
        question.setAnalysis(questionData.getAnalysis());
        question.setDifficulty(questionData.getDifficulty());
        question.setTotalScore(questionData.getTotalScore());

        // 根据题目类型更新特定字段
        switch (questionData.getQuestionType()) {
            case "SINGLE_CHOICE":
            case "TRUE_FALSE":
                question.setAnswer(questionData.getAnswer());
                break;
            case "FILL_BLANK":
                question.setBlanks(String.join("|", questionData.getBlanks()));
                question.setScore(questionData.getScore());
                break;
            case "READING":
                question.setPassage(questionData.getPassage());
                break;
        }

        // 更新题目基本信息
        questionMapper.updateQuestion(question);

        // 删除旧的关联数据
        deleteRelatedData(id);

        // 重新添加选项
        if (questionData.getOptions() != null) {
            for (QuestionData.Option option : questionData.getOptions()) {
                QuestionOption questionOption = new QuestionOption();
                questionOption.setQuestionId(id);
                questionOption.setOptionId(option.getOptionId());
                questionOption.setContent(option.getContent());
                questionMapper.insertOption(questionOption);
            }
        }

        // 重新添加多选题答案
        if ("MULTIPLE_CHOICE".equals(questionData.getQuestionType()) && questionData.getAnswers() != null) {
            for (String answer : questionData.getAnswers()) {
                MultipleChoiceAnswer multipleAnswer = new MultipleChoiceAnswer();
                multipleAnswer.setQuestionId(id);
                multipleAnswer.setOptionId(answer);
                questionMapper.insertMultipleChoiceAnswer(multipleAnswer);
            }
        }

        // 重新添加答案要点
        if (questionData.getKeyPoints() != null) {
            for (QuestionData.KeyPoint keyPoint : questionData.getKeyPoints()) {
                AnswerKeyPoint point = new AnswerKeyPoint();
                point.setQuestionId(id);
                point.setPoint(keyPoint.getPoint());
                point.setScore(keyPoint.getScore());
                questionMapper.insertKeyPoint(point);
            }
        }

        // 重新添加标签
        if (questionData.getTags() != null) {
            for (String tag : questionData.getTags()) {
                questionMapper.insertTag(id, tag);
            }
        }

        // 重新添加知识点
        if (questionData.getKnowledgePoints() != null) {
            for (String knowledgePoint : questionData.getKnowledgePoints()) {
                questionMapper.insertKnowledgePoint(id, knowledgePoint);
            }
        }

        // 如果是阅读理解题，更新子题目
        if ("READING".equals(questionData.getQuestionType()) && questionData.getSubQuestions() != null) {
            // 删除旧的子题目
            List<Long> oldSubQuestionIds = questionMapper.getSubQuestionIds(id);
            for (Long subId : oldSubQuestionIds) {
                deleteQuestionById(subId);
            }

            // 添加新的子题目
            for (QuestionData.SubQuestion subQuestion : questionData.getSubQuestions()) {
                Question subQuestionEntity = new Question();
                subQuestionEntity.setQuestionType("SUB_QUESTION");
                subQuestionEntity.setParentId(id);
                subQuestionEntity.setStem(subQuestion.getStem());
                subQuestionEntity.setAnswer(subQuestion.getAnswer());
                subQuestionEntity.setAnalysis(subQuestion.getAnalysis());
                subQuestionEntity.setScore(subQuestion.getScore());
                
                questionMapper.insertQuestion(subQuestionEntity);
                Long subQuestionId = subQuestionEntity.getId();

                // 添加子题目的选项
                if (subQuestion.getOptions() != null) {
                    for (QuestionData.Option option : subQuestion.getOptions()) {
                        QuestionOption questionOption = new QuestionOption();
                        questionOption.setQuestionId(subQuestionId);
                        questionOption.setOptionId(option.getOptionId());
                        questionOption.setContent(option.getContent());
                        questionMapper.insertOption(questionOption);
                    }
                }
            }
        }

        // 返回更新后的完整题目信息
        return questionMapper.getQuestionWithDetailsById(id);
    }
} 